package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description WechatServiceImpl
 * @Author KangChi Wang
 * @Date 2024-08-30
 */
@Service
@Slf4j
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.wechat.appId}")
    private String appId;

    @Value("${zzyl.wechat.appSecret}")
    private String secret;

    /**
     * 获取openid
     *
     * @param code 登录凭证
     * @return
     * @throws IOException
     */
    @Override
    public String getOpenid(String code) {
        //定义map存放参数
        Map<String, Object> map=new HashMap<>();
        map.put("secret", secret);
        map.put("appid", appId);
        map.put("js_code", code);
        //请求书库
        String josn = HttpUtil.get(REQUEST_URL, map);
        //josn的字符串转为josn
        JSONObject jsonObject = JSONUtil.parseObj(josn);
        //判断是否有错
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new BaseException(BasicEnum.GET_PHONE_ERROR);
        }
        return jsonObject.get("openid").toString();
    }

    @Override
    public String getPhone(String code) {
        //定义map存放参数
        Map<String, Object> map=new HashMap<>();
        map.put("code", code);
        String path = PHONE_REQUEST_URL+getAccessToken();
        //请求书库
        String josn = HttpUtil.post(path, JSONUtil.toJsonStr(map));
        //josn的字符串转为josn
        JSONObject jsonObject = JSONUtil.parseObj(josn);
        //判断是否有错

        Integer errcode = Integer.parseInt(jsonObject.get("errcode").toString());
        if (errcode != null && errcode!=0){
            throw new BaseException(BasicEnum.GET_PHONE_ERROR);
        }
        return jsonObject.getJSONObject("phone_info").get("purePhoneNumber").toString();
    }

    /**
     * 获取access_token
     * @return {@link String }
     */
    public String getAccessToken(){
        //定义map存放参数
        Map<String, Object> map=new HashMap<>();
        map.put("secret", secret);
        map.put("appid", appId);

        //请求token
        String josn = HttpUtil.get(TOKEN_URL, map);
        //josn的字符串转为josn
        JSONObject jsonObject = JSONUtil.parseObj(josn);
        //判断是否有错
        if(jsonObject.containsKey("errcode")){
            log.error("获取openid失败：{}", jsonObject.getStr("errmsg"));
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }
        return jsonObject.get("access_token").toString();
    }


}
